package com.smg.community.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;


import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

@SuppressWarnings("restriction")
public class ImageCutUtil {
	/**
	 * @author <a href="mailto:lqinglong@yahoo.cn">qinglong.lu</a>
	 * 2008-3-21
	 */
	private String srcpath ;//===源图片路锟斤拷锟斤拷锟斤拷锟�c:/1.jpg
	private String subpath ;//===锟斤拷锟斤拷图片锟斤拷锟铰凤拷锟斤拷锟斤拷.锟斤拷:c:/2.jpg
	
	private int x;//===锟斤拷锟叫碉拷x锟斤拷锟�
	private int y;//===锟斤拷锟叫碉拷y锟斤拷锟�
	
	private int cutWidth;//===锟斤拷锟叫碉拷锟斤拷
	private int cutHeight;//===锟斤拷锟叫碉拷叨锟�
	
	private int width;//锟斤拷锟斤拷锟斤拷锟斤拷锟脚碉拷图片锟斤拷锟�
	private int height;//锟斤拷锟斤拷锟斤拷锟斤拷锟脚碉拷图片锟竭讹拷
	
	public int getWidth() {
		return width;
	}
	public void setWidth(int width) {
		this.width = width;
	}
	public int getHeight() {
		return height;
	}
	public void setHeight(int height) {
		this.height = height;
	}
	
	public int getCutWidth() {
		return cutWidth;
	}
	public void setCutWidth(int cutWidth) {
		this.cutWidth = cutWidth;
	}
	public int getCutHeight() {
		return cutHeight;
	}
	public void setCutHeight(int cutHeight) {
		this.cutHeight = cutHeight;
	}
	
	
	
	public ImageCutUtil(int x,int y,int cutWidth,int cutHeight){
	     this.x = x ;
	     this.y = y ;
	     this.cutWidth = cutWidth;
	     this.cutHeight = cutHeight;
	}
	
	public ImageCutUtil(int x,int y,int cutWidth,int cutHeight,int width,int height){
	     this.x = x ;
	     this.y = y ;
	     this.cutWidth = cutWidth;
	     this.cutHeight = cutHeight;
	     this.width = width;
	     this.height = height;
	}
	
    public String getSrcpath(){
        return srcpath;
    }
    public void setSrcpath(String srcpath){
        this.srcpath = srcpath;
    }
    public String getSubpath(){
        return subpath;
    }
    public void setSubpath(String subpath){
        this.subpath = subpath;
    }

    public int getX(){
        return x;
    }
    public void setX(int x){
        this.x = x;
    }
    public int getY(){
        return y;
    }
    public void setY(int y){
        this.y = y;
    } 
    /**
     * 锟斤拷图片锟矫硷拷锟斤拷锟斤拷锟窖裁硷拷锟斤拷锟斤拷锟酵计拷锟斤拷锟�
     * @param suffixName 图片锟斤拷缀锟斤拷
     */
    public void cut(String suffixName,String datePath){
    	String picName = subpath.substring(subpath.lastIndexOf("/")+1, subpath.length());
    	String basePic = subpath.substring(0, subpath.lastIndexOf("/"));
    	String smallPic = basePic  + "/" +datePath + "/" + picName;
        File smallFile = new File(smallPic);
        if (!smallFile.exists()) {
        	smallFile.mkdirs();
        }
        FileInputStream is = null ;
        ImageInputStream iis =null ;
        try{
            //锟斤拷取图片锟侥硷拷
            is = new FileInputStream(srcpath);
            /*
             * 锟斤拷锟截帮拷锟斤拷锟叫碉拷前锟斤拷注锟斤拷 ImageReader 锟斤拷 Iterator锟斤拷锟斤拷些 ImageReader
             * 锟斤拷锟斤拷芄锟斤拷锟斤拷锟街革拷锟斤拷锟绞斤拷锟�锟斤拷锟斤拷formatName - 锟斤拷锟斤拷锟绞斤拷锟绞斤拷锟斤拷 .
             *锟斤拷锟斤拷锟斤拷 "jpeg" 锟斤拷 "tiff"锟斤拷锟斤拷 锟斤拷 
             */
            Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(suffixName);
            ImageReader reader = it.next();
            //锟斤拷取图片锟斤拷
            iis = ImageIO.createImageInputStream(is);
            /*
             * <p>iis:锟斤拷取源.true:只锟斤拷前锟斤拷锟斤拷 </p>
             * 锟斤拷锟斤拷锟斤拷为 锟斤拷只锟斤拷前锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷味锟脚帮拷锟斤拷锟斤拷锟斤拷源锟叫碉拷图锟斤拷只锟斤拷顺锟斤拷锟饺★拷锟斤拷锟斤拷锟斤拷锟斤拷锟�reader
             * 锟斤拷锟解缓锟斤拷锟斤拷锟斤拷锟角帮拷丫锟斤拷锟饺★拷锟酵硷拷锟斤拷锟斤拷锟斤拷锟斤拷莸锟斤拷锟叫╋拷锟斤拷氩匡拷帧锟�
             */
            reader.setInput(iis,true);
            
            /*
             * <p>锟斤拷锟斤拷锟斤拷味锟斤拷锟斤拷锟斤拷薪锟斤拷锟斤拷锟斤拷<p>.
             * 锟斤拷锟斤拷指锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟绞憋拷锟�Java Image I/O 锟斤拷艿锟斤拷锟斤拷锟斤拷锟斤拷械锟斤拷锟阶拷锟揭伙拷锟酵硷拷锟斤拷一锟斤拷图锟斤拷锟斤拷锟斤拷锟截讹拷图锟斤拷
             * 锟斤拷式锟侥诧拷锟斤拷锟斤拷锟斤拷锟�ImageReader 实锟街碉拷 getDefaultReadParam 锟斤拷锟斤拷锟叫凤拷锟斤拷 ImageReadParam 锟斤拷实锟斤拷
             */
            ImageReadParam param = reader.getDefaultReadParam();
            
            
            BufferedImage sourceImg = getImage(srcpath);
            /*
             * 图片锟矫硷拷锟斤拷锟斤拷Rectangle 指锟斤拷锟斤拷锟斤拷锟秸硷拷锟叫碉拷一锟斤拷锟斤拷锟斤拷通锟斤拷 Rectangle 锟斤拷锟斤拷
             * 锟斤拷锟斤拷锟较讹拷锟斤拷锟斤拷锟疥（x锟斤拷y锟斤拷锟斤拷锟斤拷群透叨瓤锟斤拷远锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷
             * 
             * 锟斤拷锟斤拷锟斤拷锟斤拷原图锟叫革拷锟斤拷锟揭拷牟锟斤拷帧锟斤拷懈锟斤拷锟揭拷牟锟斤拷锟斤拷锟絇ointX锟斤拷PointY锟斤拷CutWidth锟斤拷CutHeight锟斤拷
             * 锟斤拷为锟节客伙拷锟剿的筹拷锟斤拷锟斤拷锟角匡拷锟斤拷锟斤拷锟斤拷原图锟斤拷锟斤拷锟斤拷锟叫革拷模锟斤拷锟斤拷锟揭拷锟斤拷锟斤拷懈锟皆际憋拷锟揭拷劝锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟叫╋拷锟斤拷锟�
             * 锟斤拷要注锟斤拷PointX锟斤拷CutWidth锟斤拷要水平锟斤拷锟斤拷谋锟斤拷锟絇ointY锟斤拷CutHeight锟斤拷要锟斤拷直锟斤拷锟斤拷谋锟斤拷锟斤拷锟斤拷纾拷锟斤拷锟絠mgPhoto锟斤拷原图锟斤拷锟斤拷
             * 
             * 水平锟叫革拷悖篜ointX * imgPhoto.Width / PicWidth锟斤拷
             * 锟叫革拷锟饺ｏ拷CutWidth * imgPhoto.Width / PicWidth锟斤拷
             * 锟斤拷直锟叫革拷悖篜ointY * imgPhoto.Height / PicHeight锟斤拷
             * 锟叫革拷叨龋锟紺utHeight * imgPhoto.Height / PicHeight锟斤拷
             */ 
            Rectangle rect = new Rectangle(x * sourceImg.getWidth() / width, 
            		y * sourceImg.getHeight() / height, 
            		cutWidth * sourceImg.getWidth() / width, 
            		cutHeight * sourceImg.getHeight() / height);
            
            //锟结供一锟斤拷 BufferedImage锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷莸锟侥匡拷锟�
            param.setSourceRegion(rect); 
            
            /*
             * 使锟斤拷锟斤拷锟结供锟斤拷 ImageReadParam 锟斤拷取通锟斤拷锟斤拷锟斤拷 imageIndex 指锟斤拷锟侥讹拷锟襟，诧拷锟斤拷
             * 锟斤拷锟斤拷为一锟斤拷锟斤拷锟斤拷锟�BufferedImage 锟斤拷锟截★拷
             */
            BufferedImage bi = reader.read(0,param);
            
        	ImageIO.write(resizeImg(bi,170,170), suffixName, smallFile);
           // System.out.println("图片锟斤拷锟斤拷锟斤拷锟�);
        } catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(is != null)is.close();
				if(iis != null)iis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
    }
    
    public BufferedImage resizeImg(BufferedImage src,Integer width,Integer heigth){
    	Image image = src.getScaledInstance(width,heigth,Image.SCALE_DEFAULT);
        BufferedImage target = new BufferedImage(width,heigth,BufferedImage.TYPE_INT_RGB);
    	Graphics g = target.getGraphics();
    	g.drawImage(image, 0, 0, null); // 锟斤拷锟斤拷锟斤拷小锟斤拷锟酵�
    	g.dispose();
		return target;
    }
    
    /**
    * 锟睫革拷图片锟斤拷小
    */
    public void alterSize(String srcImgFile,String addChar,int newWidth,int newHeight,String root){
	    //System.out.print("锟侥硷拷路锟斤拷为:"+"//"+srcImgFile);
	    //String root = session.getServletContext().getRealPath("/");
	    java.io.File file = new java.io.File(root + srcImgFile);
	    if(file.exists()){
	    	System.out.println("锟侥硷拷锟斤拷锟斤拷");
	    }else{
	    	System.out.println("锟侥硷拷锟斤拷锟斤拷锟斤拷");
	    }
	    int i = srcImgFile.indexOf(".");
	    int sLen = srcImgFile.length();
	    String suffix = srcImgFile.substring(i, sLen); //锟斤拷锟�锟斤拷缀锟斤拷
	    String urlName = srcImgFile.substring(0,i); //路锟斤拷+锟侥硷拷锟斤拷
	    String newUrlName = root + urlName + addChar + suffix;
	    //System.out.print("锟斤拷锟侥硷拷锟斤拷为"+newUrlName);
	    Image src = null;
	    try{
		    src = javax.imageio.ImageIO.read(file);
		    java.awt.image.BufferedImage tag = new java.awt.image.BufferedImage(newWidth,newHeight,java.awt.image.BufferedImage.TYPE_INT_ARGB);
		    tag.getGraphics().drawImage(src,0,0,newWidth,newHeight,null);
		    FileOutputStream newimage = new FileOutputStream(newUrlName);
		    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
		    encoder.encode(tag); //锟斤拷JPEG锟斤拷锟斤拷
		    newimage.close();
	    }catch(IOException ee){
		    ee.printStackTrace();
		  //  System.out.print("锟斤拷锟斤拷锟斤拷锟斤拷锟�);
	    }catch(Exception e){
	    	e.printStackTrace();
	    }
    }//End sizeAlter
    
    /** 
     * 锟斤拷图片印刷锟斤拷图片锟斤拷
     *  @param  pressImg -- 水印锟侥硷拷
     *  @param  targetImg  -- 目锟斤拷锟侥硷拷
     *  @param  x
     *  @param  y
    */ 
    public final static void pressImage(String pressImg, String targetImg) {
    	try{
    		File _file  =   new  File(targetImg);
    		Image src  =  ImageIO.read(_file);
    		int  width  =  src.getWidth( null );
    		int  height  =  src.getHeight( null );
    		BufferedImage image  =   new  BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
    		Graphics g  =  image.createGraphics();
    		g.drawImage(src,  0 ,  0 , width, height,  null );
    		//水印锟侥硷拷 
    		File _filebiao  =   new  File(pressImg);
    		Image src_biao  =  ImageIO.read(_filebiao);
            int  width_biao  =  src_biao.getWidth( null );
            int  height_biao  =  src_biao.getHeight( null );
            g.drawImage(src_biao,width-width_biao,height-height_biao, width_biao,height_biao,  null );
            g.dispose();
            FileOutputStream out  =   new  FileOutputStream(targetImg);
            JPEGImageEncoder encoder  =  JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
            param.setQuality(50f, true);
            encoder.encode(image, param);
            out.close();
    	} catch (Exception e)  {
    		e.printStackTrace();
    	}
    }
    //锟斤拷水印
    public static boolean createMarkStr(String filePath,String strmark) {
    	ImageIcon imgIcon = new ImageIcon(filePath);
        Image theImg = imgIcon.getImage();
		int offWidth = 250;//水印锟斤拷锟狡拷频锟轿伙拷锟�
        int width = theImg.getWidth(null);
        int height = theImg.getHeight(null);
        BufferedImage bimage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bimage.createGraphics();
        //锟斤拷锟斤拷水印锟斤拷锟斤拷
        Font font1 = null;
        if(width>800 || height>600){
        	font1 = new Font("锟斤拷锟斤拷", Font.PLAIN, 18);
			offWidth = 350;
        }else{
        	font1 = new Font("锟斤拷锟斤拷", Font.PLAIN, 12);
        }
        g.setFont(font1);
        g.setColor(Color.WHITE);
        g.drawImage(theImg, 0, 0, null);
        g.drawImage(theImg, width, height, null);
        if(width>140)
        	g.drawString(strmark,width-offWidth, height-8); //锟斤拷锟斤拷锟斤拷锟�
        else if(width>20)
        	g.drawString("DDCLUB.GSUO.COM",5, height-15); //锟斤拷锟斤拷锟斤拷锟�
        g.dispose();
        try {
        	FileOutputStream out = new FileOutputStream(filePath);
        	JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        	JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
        	param.setQuality(50f, true);
        	encoder.encode(bimage, param);
        	out.close();
        }
        catch (Exception e) {
        	return false;
        }
        return true;
    }
    /**
     * 锟斤拷锟酵计凤拷锟斤拷锟饺⊥计�
     * */
    public static BufferedImage getImage(String imgUrl){
    	File file = new File(imgUrl);
        FileInputStream is = null;
        try{
            is = new FileInputStream(file);
        }catch (FileNotFoundException e2){
            e2.printStackTrace();
            //return rect;
        }
        BufferedImage sourceImg = null;
        try{
            sourceImg = javax.imageio.ImageIO.read(is);
        }catch (IOException e1){
            e1.printStackTrace();
            //return rect;
        }
        //System.out.println("width = "+sourceImg.getWidth() + "height = " + sourceImg.getHeight());
        return sourceImg;
    }
    public static void main(String[] args)throws Exception{
        String fileName = "C:\\Users\\xiaomage\\Desktop\\head\\02.gif";
        //String fileName = "D:\\Workspaces\\eclipse 3.7\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp4\\wtpwebapps\\ddmap-web-user\\UserHead\\20111207151332250.jpg";
        ImageCutUtil iu = new ImageCutUtil(0,0,93,93);
        iu.setSrcpath(fileName);
        //iu.setSubpath("C:\\Users\\xiaomage\\Desktop\\锟斤拷锟斤拷页锟斤拷929\\images\\M1/201110271441.png");
        iu.setSubpath("D:\\Workspaces\\eclipse 3.7\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp4\\wtpwebapps\\ddmap-web-user\\UploadUserHead\\02.gif");
        iu.cut("gif","2012-01");   
    }
}
